import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Collapse} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FORM_ROW_OPTIONS, FILES_API} from '../constants';
import {upgradeData, getDetail} from './api';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {kDClaimType, claimCompensationWay, urgencyLevel, claimPartType, claimTransportType, isYesNo} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import {injectIntl, language} from './intl';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
const {Description} = DescriptionList;
import {upgradeOrUpdateOrderValidator} from './validator';
const {Panel} = Collapse;
const FormItem = Form.Item;

const isYesNoToList = isYesNo.toList(language);
class UpgradePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: [],
        partDetails: [],
        claimDetails: [],
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                        partDetails: res.data.details.partDetails,
                        claimDetails: res.data.claimDetails,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const isValid = upgradeOrUpdateOrderValidator(details);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            rowVersion: data.rowVersion,
            details: details.map(v => ({
                id: v.id,
                qualityIsClaim: v.qualityIsClaim === 1,
                qualityComment: v.qualityComment,
            })),
        };
        this.setState({loading: true});
        upgradeData(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onChangeAll = (value, id, e) => {
        const details = this.state.details || [];
        const name = e.target.name;
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onUpdateisFromQualityIsClaim = (qualityIsClaim, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    qualityIsClaim,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details = {}, claimDetails = [], isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const partColumns = [{
            title: formatMessage({
                id: 'upgradePanel.column.shipPartCode',
                defaultMessage: '发运单零件号'
            }),
            dataIndex: 'shipPartCode',
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.shipPartName',
                defaultMessage: '发运零件名称'
            }),
            dataIndex: 'shipPartName',
        }, {
            title: formatMessage({
                id: 'upgradePanel.colums.quantity',
                defaultMessage: '索赔数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.partCodeAfter',
                defaultMessage: '更改后零件号'
            }),
            dataIndex: 'partCodeAfter',
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.partNameAfter',
                defaultMessage: '更改后零件名称'
            }),
            dataIndex: 'partNameAfter',
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.isFromKDBOM',
                defaultMessage: '是否来自KDBOM'
            }),
            dataIndex: 'isFromKDBOM',
            render: text => text ? formatMessage({
                id: 'upgradePanel.column.y',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'upgradePanel.column.n',
                defaultMessage: '否'
            }),
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.isSubPart',
                defaultMessage: '是否SUB件'
            }),
            dataIndex: 'isSubPart',
            render: text => text ? formatMessage({
                id: 'upgradePanel.column.y',
                defaultMessage: '是'
            }) : formatMessage({
                id: 'upgradePanel.column.n',
                defaultMessage: '否'
            }),
        }, {
            title: formatMessage({
                id: 'upgradePanel.column.supplierCode',
                defaultMessage: '供应商代码'
            }),
            dataIndex: 'supplierCode',
        }];
        const aaa = [];
        details.forEach(item =>
            aaa.push(<Panel header={item.kdBomCode} key={item.id}>
                <DescriptionList size="large">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.quantity',
                            defaultMessage: '索赔数量'
                        })}{...FORM_OPTIONS.item}>
                            {item.quantity}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.dutyUnitId',
                            defaultMessage: '责任单位'
                        })}{...FORM_OPTIONS.item}>
                            {item.dutyUnitCode === undefined ? '' : `(${item.dutyUnitCode})${item.dutyUnitName}`}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.productCategoryId',
                            defaultMessage: '车型'
                        })}{...FORM_OPTIONS.item}>
                            {item.productCategoryName}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.engineModel',
                            defaultMessage: '发动机型号'
                        })}{...FORM_OPTIONS.item}>
                            {item.engineModel}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.transmissionModel',
                            defaultMessage: '变速箱型号'
                        })}{...FORM_OPTIONS.item}>
                            {item.transmissionModel}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.engineCode',
                            defaultMessage: '发动机号'
                        })}{...FORM_OPTIONS.item}>
                            {item.engineCode}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.transmissionSn',
                            defaultMessage: '变速箱号'
                        })}{...FORM_OPTIONS.item}>
                            {item.transmissionSn}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.vehicleFrameCode',
                            defaultMessage: '车架码'
                        })}{...FORM_OPTIONS.item}>
                            {item.vehicleFrameCode}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partclaimPanel.data.mfgIsClaim',
                            defaultMessage: '制造中心确认索赔'
                        })}{...FORM_OPTIONS.item}>
                            {conventEnumValueToString(isYesNo, (item.mfgIsClaim === true || item.mfgIsClaim === 1) ? 1 : 0)}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'partclaimPanel.data.mfgComment',
                            defaultMessage: '制造中心意见'
                        })}{...FORM_OPTIONS.item}>
                            {item.mfgComment}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.planIsClaim',
                            defaultMessage: '计划部确认索赔'
                        })}{...FORM_OPTIONS.item}>
                            {conventEnumValueToString(isYesNo, (item.planIsClaim === true || item.planIsClaim === 1) ? 1 : 0)}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.planComment',
                            defaultMessage: '计划部意见'
                        })}{...FORM_OPTIONS.item}>
                            {item.planComment}
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.qualityIsClaim',
                            defaultMessage: '质管中心确认索赔'
                        })}{...FORM_OPTIONS.item} validateStatus={isValidate && item.qualityIsClaim !== 0 &&
                            item.qualityIsClaim !== 1 && item.qualityIsClaim !== true && data.qualityIsClaim !== false ? 'error' : null} required>
                            <WrappedSelect
                                allowClear
                                name="qualityIsClaim"
                                options={isYesNoToList}
                                value={(item.qualityIsClaim === true || item.qualityIsClaim === 1) ? 1 : 0}
                                onChange={this.onUpdateisFromQualityIsClaim}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'upgradePanel.data.qualityComment',
                            defaultMessage: '质管中心意见'
                        })}{...FORM_OPTIONS.item}>
                            <TextInput
                                name="qualityComment"
                                value={item.qualityComment}
                                onBlur={this.onChangeAll} />
                        </FormItem>
                    </Col>
                </DescriptionList>
                <div className={styles.description}>
                    <Table
                        className="white-space-nowrap"
                        columns={partColumns}
                        rowKey="shipPartId"
                        pagination={false}
                        dataSource={item.partDetails}
                        {...TABLE} />
                </div>
            </Panel>
            ));
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'upgradePanel.column.common',
                        defaultMessage: '索赔信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.code',
                                        defaultMessage: '申请单号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.brandCode}){data.brandName}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'upgradePanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.dealerCode}){data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.country',
                                        defaultMessage: '国家'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.claimType',
                                        defaultMessage: '索赔类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(kDClaimType, data.claimType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.claimPartType',
                                        defaultMessage: '索赔配件类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(claimPartType, data.claimPartType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.data.saleShipmentId',
                                        defaultMessage: '发运单编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.saleShipmentCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.batchNumber',
                                        defaultMessage: '批次号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.batchNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.urgencyLevel',
                                        defaultMessage: '紧急程度'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(urgencyLevel, data.urgencyLevel)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.requireCompensationWay',
                                        defaultMessage: '需求赔付方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(claimCompensationWay, data.requireCompensationWay)}
                                    </FormItem>
                                </Col>
                                {claimCompensationWay.零件赔付 ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.requireTransportType',
                                        defaultMessage: '需求运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(claimTransportType, data.requireTransportType)}
                                    </FormItem>
                                </Col> : data.requireTransportType === undefined}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.actualCompensationWay',
                                        defaultMessage: '实际赔付方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(claimCompensationWay, data.actualCompensationWay)}
                                    </FormItem>
                                </Col>
                                {data.actualCompensationWay === claimCompensationWay.零件赔付 ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.actualTransportType',
                                        defaultMessage: '实际运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(claimTransportType, data.actualTransportType)}
                                    </FormItem>
                                </Col> : data.actualTransportType === undefined}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.containerNumber',
                                        defaultMessage: '集装箱号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.containerNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.boxNumber',
                                        defaultMessage: '纸箱号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.boxNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.caseNumber',
                                        defaultMessage: '箱号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.caseNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.bLNumber',
                                        defaultMessage: '提单号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.bLNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.bLDate',
                                        defaultMessage: '提单日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.bLDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.description',
                                        defaultMessage: '索赔详细描述'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.description}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'upgradePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'upgradePanel.operation.detail',
                            defaultMessage: 'KD索赔清单'
                        })}>
                        <Collapse>
                            {aaa}
                        </Collapse>
                    </Card>
                    <Card title={formatMessage({
                        id: 'upgradePanel.title.claimDetailFiles',
                        defaultMessage: '索赔资料附件清单'
                    })}>
                        {claimDetails && claimDetails.length >= 0
                            ? <DescriptionList>
                                {claimDetails.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">
                                        {item.fileName}</a></Description>))}
                            </DescriptionList>
                            : <DescriptionList title={formatMessage({
                                id: 'upgradePanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })} />}
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'upgradePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpgradePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpgradePanel));
